﻿using MSXML2;


namespace RtaInfoCMD
{
	/// <summary>
	/// A simple wrapper providing access to Matrix object information and MQL query results.
	/// </summary>
	class MatrixInterface
	{
		private const string MqlUrl = @"http://cwiprod.corp.halliburton.com/cwi/just_mql.jsp?user=tmp&ignorePasswd=true&input=";
		private const string MqlPrintBase = @"print bus Rta R00000[RTANUM] '' select [SELECT] dump |";


		/// <summary>
		/// Returns the description of a given RTA
		/// </summary>
		/// <param name="rtaNum">The RTA number.</param>
		public static string GetDescription(string rtaNum)
		{
			string qry = MqlPrintBase.Replace("[RTANUM]", rtaNum).Replace("[SELECT]", "description");
			return GetResponse(qry);
		}


		/// <summary>
		/// Returns the ID of a given RTA
		/// </summary>
		/// <param name="rtaNum">The RTA number.</param>
		public static string GetId(string rtaNum)
		{
			string qry = MqlPrintBase.Replace("[RTANUM]", rtaNum).Replace("[SELECT]", @"id");
			return GetResponse(qry);
		}

		
		/// <summary>
		/// Returns the Customer Name attribute of a given RTA
		/// </summary>
		/// <param name="rtaNum">The RTA number.</param>
		public static string GetCustomer(string rtaNum)
		{
			string qry = MqlPrintBase.Replace("[RTANUM]", rtaNum).Replace("[SELECT]", "attribute[Customer Name]");
			return GetResponse(qry);
		}

		
		/// <summary>
		/// Returns the comments of a given RTA
		/// </summary>
		/// <param name="rtaNum">The RTA number.</param>
		public static string GetComments(string rtaNum)
		{
			string qry = MqlPrintBase.Replace("[RTANUM]", rtaNum).Replace("[SELECT]", "attribute[Comments]");
			return GetResponse(qry);
		}

		
		/// <summary>
		/// Returns the value of the specified attribute for the given RTA.
		/// </summary>
		/// <param name="rtaNum">The RTA number.</param>
		/// <param name="attribute">The name of the attribute to query.</param>
		public static string GetAttribute(string rtaNum, string attribute)
		{
			string qry = MqlPrintBase.Replace("[RTANUM]", rtaNum).Replace("[SELECT]", "attribute[" + attribute + "]");
			return GetResponse(qry);
		}

		
		/// <summary>
		/// Returns the response of the given MQL query string. 
		/// </summary>
		/// <param name="query">An MQL query string.</param>
		private static string GetResponse(string query)
		{
			var oXml = new XMLHTTP60();
			oXml.open("POST", MqlUrl + query);
			oXml.send();
			var result = oXml.responseText;
			return result.Trim();
		}
	}
}
